package kz.asoft;


import java.awt.Color;

import java.util.ArrayList;
import java.util.List;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;

import kz.asoft.am.common.RisksAppModule;
import kz.asoft.utils.ADFUtils;
import kz.asoft.utils.Utils;

import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.faces.bi.component.pivotTable.CellFormat;
import oracle.adf.view.faces.bi.component.pivotTable.HeaderCellContext;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.nav.RichCommandButton;
import oracle.adf.view.rich.render.ClientEvent;

import oracle.bali.ewt.graphics.ColorUtils;

import oracle.dss.util.QDR;

import oracle.jbo.Row;
import oracle.jbo.RowSetIterator;
import oracle.jbo.ViewObject;
import oracle.jbo.domain.Number;
import oracle.jbo.uicli.binding.JUCtrlValueBinding;


public class CtrlObjManageBean {
    private RichInputText searchText;
    private List<SelectItem> selectItems;

    public CtrlObjManageBean() {
    }

    /**
     * Просмотр анализа рисков
     * @param actionEvent
     */
    public void viewFormData(ActionEvent actionEvent) {
        JUCtrlValueBinding ctrlObjView =
            ADFUtils.findCtrlBinding("SCtrlObjsView1");
        Row row = ctrlObjView.getIteratorBinding().getCurrentRow();
        DCIteratorBinding iterBind =
            ADFUtils.findIterator("SCtrlObjsView1Iterator");
        iterBind.setCurrentRowWithKeyValue(row.getAttribute("Id").toString());
    }

    /**
     * Формирование БД для анализа рисков, анализ рисков
    */
    public String createFormData() {
        DCIteratorBinding iterBind = ADFUtils.findIterator("GRisksCurrentView1Iterator");
        RowSetIterator rs = iterBind.getRowSetIterator();
        boolean hasEmptyValues = false;
        while(rs.hasNext()){
            Row r = rs.next();
            if(r.getAttribute("RiskValue") == null){
                hasEmptyValues = true;
                break;
            }
        }
        if(hasEmptyValues){
            FacesMessage message = new FacesMessage(Utils.getLocalizedText("MESSAGE_CTRL_OBJ_RISK_VALUES"));
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext fc = FacesContext.getCurrentInstance();
            fc.addMessage(null, message);
            return null;
        }
        RisksAppModule appModule =
            (RisksAppModule)ADFUtils.getApplicationModuleForDataControl("RisksAppModuleDataControl");
        appModule.createFormData();
        return "back";
    }

    /**
     * Поиск по наименованию объекта контроля
     * @param actionEvent
     */
    public void searchCtrlObj(ActionEvent actionEvent) {
        RisksAppModule appModule =
            (RisksAppModule)ADFUtils.getApplicationModuleForDataControl("RisksAppModuleDataControl");
        appModule.searchCtrlObj(searchText.getValue() == null ? "" : searchText.getValue().toString());
    }
    
    /**
     * Посдчёт показателей квазигос-ых субъектов
     */
    public void loadData() {
        RisksAppModule appModule =
            (RisksAppModule)ADFUtils.getApplicationModuleForDataControl("RisksAppModuleDataControl");
        appModule.setRiskValuesByFormula();
    }
    
    /**
     * Получение списка значений рисков(текстовые значения)
     * @return
     */
    public List<SelectItem> getSelectItems() {
        selectItems = new ArrayList<SelectItem>();
        FacesContext fctx = FacesContext.getCurrentInstance();
        ELContext elctx = fctx.getELContext();
        ExpressionFactory efactory =
            fctx.getApplication().getExpressionFactory();
        ValueExpression ve =
            efactory.createValueExpression(elctx, "#{row}", Object.class);
        //Get row
        JUCtrlValueBinding row =
            (JUCtrlValueBinding)ve.getValue(elctx);
        if (!row.getAttribute("ValuesListCount").toString().equals("0")) {
            RisksAppModule appModule =
                (RisksAppModule)ADFUtils.getApplicationModuleForDataControl("RisksAppModuleDataControl");
            appModule.getRiskListValuesByRiskId((Number)row.getAttribute("Id"));
            RowSetIterator iterator =
                appModule.findViewObject("SRiskListValuesView2").createRowSetIterator(null);
            while (iterator.hasNext()) {
                Row r = iterator.next();
                SelectItem item = new SelectItem();
                item.setLabel(r.getAttribute("Name").toString());
                item.setValue(Integer.valueOf(r.getAttribute("Id").toString()));
                selectItems.add(item);
            }
        }
        return selectItems;
    }
    
    /**
     * Анализ рисков
     * @param actionEvent
     */
    public void riskReport(ActionEvent actionEvent) {
        RisksAppModule appModule =
            (RisksAppModule)ADFUtils.getApplicationModuleForDataControl("RisksAppModuleDataControl");
        ViewObject riskReportVO = appModule.findViewObject("SCtrlObjRiskReportView1");
        riskReportVO.executeQuery();
    }
    
    /**
     * Custom header format for ctrl obj risk report
     * @param headerCellContext
     * @return
     */
    public CellFormat headerFormat(HeaderCellContext headerCellContext) {
        CellFormat cellFormat = new CellFormat(null, null, null);
        if (headerCellContext.getValue() != null) {
            QDR qdr = headerCellContext.getQDR();
            Object name1 = qdr.getDimMember("Name1");
            Object code = qdr.getDimMember("Code");
            if (name1 != null) {
                String style = "width:100px;";
                cellFormat.setTextStyle(style);
            }else if (code != null) {
                String color = null;
                if(code.toString().equals("1")){
                    color = "background-color:" + ColorUtils.colorToHTML(Color.GREEN) + ";";    
                }else if(code.toString().equals("2") || code.toString().equals("3")){
                    color = "background-color:" + ColorUtils.colorToHTML(Color.YELLOW) + ";";   
                }else if(code.toString().equals("4") || code.toString().equals("5")){
                    color = "background-color:" + ColorUtils.colorToHTML(Color.RED) + ";";   
                }
                cellFormat.setStyle(color);
            }
        }
        return cellFormat;
    }
    
    /**
     * Call action by dbclick
     * @param clientEvent
     */
    public void dbClickEvent(ClientEvent clientEvent) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        UIViewRoot root = facesContext.getViewRoot();
        RichCommandButton button = (RichCommandButton)root.findComponent("r1:pc1:cb_db_click1");
        if (button != null) {
            ActionEvent actionEvent = new ActionEvent(button);
            actionEvent.queue();
        }
    }
    
    public void setSearchText(RichInputText searchText) {
        this.searchText = searchText;
    }

    public RichInputText getSearchText() {
        return searchText;
    }
}
